package com.link510.aitools.core.caches;


import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * 缓存管理
 */
public class CWMCache {

    private Cache<String, String> maps;

    /**
     * 单例
     */
    private static CWMCache cwmCache = null;

    /**
     * 单例
     */
    public static CWMCache getInstance() {

        if (cwmCache == null) {
            synchronized (CWMCache.class) {
                if (cwmCache != null) {
                    return cwmCache;
                }
                cwmCache = new CWMCache();
            }
        }

        return cwmCache;
    }

    /**
     * 缓存
     */
    private CWMCache() {

        maps = CacheBuilder.newBuilder()
                .expireAfterAccess(5L, TimeUnit.MINUTES)
                .expireAfterWrite(30L, TimeUnit.MINUTES)
                .concurrencyLevel(6)
                .initialCapacity(100)
                .maximumSize(1000)
                .softValues()
                .build();
    }

    /**
     * 添加缓存
     *
     * @param key   key
     * @param value 植
     * @return 返回写入状态
     */
    public boolean add(String key, String value) {

        try {
            maps.put(key, value);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }


    /**
     * 返回缓存
     *
     * @param key key
     * @return 返回写入状态
     */
    public String get(String key) {

        try {
            return maps.getIfPresent(key);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }


    /**
     * 移除缓存
     *
     * @param key key
     * @return 返回状态
     */
    public boolean remove(String key) {
        try {
            maps.invalidateAll(Collections.singletonList(key));
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }


    /**
     * 移除缓存
     *
     * @return 返回状态
     */
    public boolean removeAll() {
        try {
            maps.invalidateAll();
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

}
